#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>

using namespace std;

#define Mode 0666
#define Path "fifo"

class Fifo
{
public:
    Fifo(const string& path)
        :_path(path)
    {
        umask(0);
        int n = mkfifo(_path.c_str(),Mode);
        if(n == 0)
            cout << "mkfifo success" << endl;
        else
            cout << "mkfifo failed, errno: " << errno << ", errstring: " << strerror(errno) <<  endl;
    }
    ~Fifo()
    {
        int n = unlink(_path.c_str());
        if(n == 0)
            cout << "remove fifo file " << _path << " success" << endl;
        else
            cout << "remove failed, errno: " << errno << ", errstring: " << strerror(errno) <<  endl;
    }
private:
    string _path;//文件路径 + 文件名
};


class Sync
{
public:
    Sync()
        :_rfd(-1)
        ,_wfd(-1)
    {}
    void OpenRead()
    {
        _rfd = open(Path, O_RDONLY);
        if(_rfd < 0)
            exit(1);
    }
    void OpenWrite()
    {
        _wfd = open(Path, O_WRONLY);
        if(_wfd < 0)
            exit(1);
    }
    bool Wait()
    {
        bool ret = true;
        uint32_t c = 0;
        ssize_t n = read(_rfd, &c, sizeof(uint32_t));
        if(n == sizeof(uint32_t))
        {
            cout << "server wakeup, begin read shm..." << endl;
        }
        else if(n == 0)
        {
            ret = false;
            return ret;
        }
        else
        {
            ret = false;
            return ret;
        }
        return ret;

        
    }
    void WakeUp()
    {
        uint32_t c = 0;
        ssize_t n = write(_wfd,&c,sizeof(uint32_t));
        assert(n == sizeof(uint32_t));
        cout << "wakeup server..." << endl;
    }
    ~Sync(){}
private:
    int _rfd;
    int _wfd;
};
#endif

